//
//  XQHud.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/1/28.
//

import UIKit

public class XQHud {
    
    public typealias CallBack = (XQPopView) -> Void
    
    private static var showPopCallBack : CallBack?
    private static var hidePopCallBack : CallBack?
    
    private class func getWindow() -> UIWindow {
        var window = UIApplication.shared.currentWindow
        //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
            let windows = UIApplication.shared.windows
            for  windowTemp in windows{
                if windowTemp.windowLevel == UIWindow.Level.normal{
                    window = windowTemp
                    break
                }
            }
        }
        return window!
    }
    
    public class func currentController () -> UIViewController? {
        let vc = getWindow().rootViewController
        return getCurrentViewController(withCurrentVC: vc)
    }
    
    private class func getCurrentViewController(withCurrentVC VC :UIViewController?) -> UIViewController? {
        if VC == nil {
            return nil
        }
        if let presentVC = VC?.presentedViewController {
            //modal出来的 控制器
            return getCurrentViewController(withCurrentVC: presentVC)
        }
        else if let splitVC = VC as? UISplitViewController {
            // UISplitViewController 的跟控制器
            if splitVC.viewControllers.count > 0 {
                return getCurrentViewController(withCurrentVC: splitVC.viewControllers.last)
            }else{
                return VC
            }
        }
        else if let tabVC = VC as? UITabBarController {
            // tabBar 的跟控制器
            if tabVC.viewControllers != nil {
                return getCurrentViewController(withCurrentVC: tabVC.selectedViewController)
            }else{
                return VC
            }
        }
        else if let naiVC = VC as? UINavigationController {
            if naiVC.viewControllers.count > 0 {
                return getCurrentViewController(withCurrentVC:naiVC.visibleViewController)
            }else{
                return VC
            }
        }
        else {
            return VC
        }
    }
}

extension XQHud {
    
    public class func showToast(message:String,
                                 config:XQToastConfig? = nil) {
        getWindow().subviews.forEach { view in
            if view.isKind(of: XQToastView.self) {
                view.removeFromSuperview()
            }
        }
        
        let co = config ?? XQToastConfig()
        
        let toast = XQToastView(message: message, config: co)
        getWindow().addSubview(toast)
        toast.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            switch co.offsetType {
            case .center:
                make.centerY.equalToSuperview()
            case .top:
                make.top.equalToSuperview().offset(co.offset)
            case .bottom:
                make.bottom.equalToSuperview().offset(-co.offset)
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + co.showTime) {
            UIView.animate(withDuration: co.animationDuration, animations: {
                toast.alpha = 0
            }) { (_) in
                toast.removeFromSuperview()
            }
        }
    }
}

extension XQHud {
    
    public typealias loadingConfig = ((_ config : XQLoadingConfig) -> Void)
    
    public class func showLoading(_ title : String? = nil,
                              config : loadingConfig? = nil,
                              controller : UIViewController? = nil) {
        
        var co : UIViewController?
        
        if (controller != nil) {
            co = controller
        }else if (currentController() != nil) {
            co = currentController()
        }
        
        let model = XQLoadingConfig()
        config?(model)
        loading(title: title,onView: co?.view, config: model)
    }
    
    public class func hideLoading( controller : UIViewController? = nil) {
        
        var co : UIViewController?
        
        if (controller != nil) {
            co = controller
        }else if (currentController() != nil) {
            co = currentController()
        }
        
        guard let vc = co else {
            return
        }

        hideLoadingOnView(vc.view)
    }
    
    public class func hideLoadingOnView(_ onView: UIView) {
        onView.subviews.forEach { (view) in
            if view.isKind(of: XQLoadingView.self){
                view.removeFromSuperview()
            }
        }
    }
    
    public class func hideLoadingOnWindow() {
        hideLoadingOnView(getWindow())
    }
    
    private class func loading(title: String? = nil,
                               onView: UIView? = nil,
                               config : XQLoadingConfig) {
        let loadingView = XQLoadingView(title: title, config: config)
        loadingView.isUserInteractionEnabled = !config.enableEvent
        if let base = onView{
            hideLoadingOnView(base)
            base.addSubview(loadingView)
            base.bringSubviewToFront(loadingView)
            loadingView.layer.zPosition = CGFloat(MAXFLOAT)
        }else{
            hideLoadingOnWindow()
            getWindow().addSubview(loadingView)
        }
        
        loadingView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
        }
    }
}


extension XQHud {
    
    public typealias popConfig = ((_ config : XQPopConfig) -> Void)
        
    public class func showPop(_ contentView: UIView,
                          controller : UIViewController? = nil,
                          config : popConfig? = nil,
                          showClosure: CallBack? = nil,
                              hideClosure: CallBack? = nil) {
        
        if (controller == nil) {
            getWindow().subviews.forEach { (view) in
                if view.isKind(of: XQPopView.self){
                    view.removeFromSuperview()
                }
            }
        }
        
        showPopCallBack = showClosure
        hidePopCallBack = hideClosure
        
        let model = XQPopConfig()
        config?(model)
        
        let popView = XQPopView.init(view: contentView, config: model) {
            hidePop(controller: controller)
        }
        
        if (controller == nil) {
            getWindow().addSubview(popView)
        }else {
            controller!.view.addSubview(popView)
        }
        
        popView.showAnimate()
        
        showPopCallBack?(popView)
    }
    
    public class func hidePop(controller : UIViewController? = nil,_ complete : (() -> Void)? = nil ) {
        if (controller == nil) {
            getWindow().subviews.forEach { (view) in
                if view.isKind(of: XQPopView.self){
                    let popView : XQPopView = view as! XQPopView
                    popView.hideAnimate {
                        UIView.animate(withDuration: 0.1, animations: {
                            view.alpha = 0
                        }) { (_) in
                            complete?()
                            view.removeFromSuperview()
                            hidePopCallBack?(popView)
                        }
                    }
                }
            }
        }else {
            for view in controller!.view.subviews.reversed() {
                if view.isKind(of: XQPopView.self){
                    let popView : XQPopView = view as! XQPopView
                    popView.hideAnimate {
                        UIView.animate(withDuration: 0.1, animations: {
                            view.alpha = 0
                        }) { (_) in
                            complete?()
                            view.removeFromSuperview()
                            hidePopCallBack?(popView)
                        }
                    }
                    break
                }
            }
        }
    }
}
